package _2响应头;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/test4")
public class Test4Servlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

		// 告诉客户端我发来的数据是图片
		resp.setContentType("image/jpeg");

		// 1. 输入流读取图片
		int id = (int) (Math.random() * 3) + 1;
		String filePath = getServletContext().getRealPath("/images/" + id + ".jpg");
		InputStream in = new FileInputStream(filePath);

		// 2. 输出流输出到resp
		OutputStream out = resp.getOutputStream();

		byte[] buf = new byte[1024];
		int len = 0;
		while ((len = in.read(buf)) != -1) {
			out.write(buf, 0, len);
		}

		// 3. 关闭流
		in.close();

	}
}
